/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import controller.EventManager;
import controller.InvitationManager;
import controller.UserManager;
import entity.Event;
import entity.Invitation;
import entity.User;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import org.primefaces.json.JSONException;


/**
 *
 * @author xubuntu
 */
@ManagedBean
@ViewScoped
public class CreateEventBean {

    @ManagedProperty( value = "#{loginBean}" )
    private LoginBean wlmPage;
    
    @ManagedProperty( value = "#{personalPageBean}" )
    private PersonalPageBean personalPageBean;
    
    @ManagedProperty( value = "#{weatherBean}" )
    private WeatherBean weatherBean;
    
    @EJB
    private UserManager usrMgr;
    
    @EJB
    private EventManager eventMgr;
    @EJB
    private InvitationManager invMgr;
    
    @ManagedProperty( value = "#{navigationBean}" )
    private NavigationBean navigationBean;
    
    private Date today = new Date();
    private Event event;
    private String eventName;
    private String description;
    private String eventPlace;
    private Date dateStart;
    private Date dateEnd= null;
    private int typeIo;
    // di default è settato privato "0"
    private int typePpInt = 0;
    private boolean typePp = false;
    private Event eventemp;

    private List<User> allUser;
    private List<User> selectedUser;

    @PostConstruct
    public void init() {
        /*
        lista di utenti escluso l'utente loggato 
        e gli utenti gia invitati (se presenti)
        necessaria per l'inserimento di invitati ad
        un evento
        */
        allUser = usrMgr.getAllUsers();
        int i = 0;
        while( i < allUser.size() )
        {
            if( allUser.get( i ).getNickname().equals(wlmPage.getUser().getNickname())==true)
                allUser.remove( i );
            else
                i++;
        }
        
        eventemp = personalPageBean.getEventSelected();
        selectedUser = new ArrayList<User>();
      
        
        if( eventemp != null && eventemp.getName().equals(""))
        {
            
            List<Invitation> invitati = new ArrayList<Invitation>();
            if(eventemp.getInvitationCollection()!= null && eventemp.getInvitationCollection().size()>0)
                invitati.addAll(eventemp.getInvitationCollection());
            
            System.out.println("invitati ha dimensione: "+invitati.size());
            if(invitati.size()>0){
                for( Invitation inv : invitati )
                {
                    if(allUser.contains(inv.getUser())){
                        allUser.remove(inv.getUser());
                    }
                    selectedUser.add( inv.getUser() );
                    System.out.println("invitato: "+inv.getUser().getNickname());
                }
            }
        }
              
    }

        public List<User> completeUser( String query ) 
    {
        List<User> filteredUser = new ArrayList<User>();
         
        for( int i = 0 ; i < allUser.size() ; i++ ) 
        {
            User skin = allUser.get( i );
            //( skin.getName() + " " + skin.getSurname() ).toLowerCase().contains( query.toLowerCase() );
            if( skin.getNickname().toLowerCase().contains( query.toLowerCase() )) {
                filteredUser.add( skin );
            }
        }
         
        return filteredUser;
    }
 

    public String createEvent() throws JSONException, IOException{

        if(dateEnd==null)
            dateEnd = dateStart;
        if(typePp==true)
            typePpInt = 1;
        
        event = new Event(eventName,eventPlace,dateStart,dateEnd,typeIo,typePpInt,description,wlmPage.getUser());
        
        // salvo ne db
        eventMgr.addEvent(event);
        /*
        controllo doppioni
        
        if(personalPageBean.getEventsTakePart().contains(event)){
            int i = 0;
            while( i < personalPageBean.getEventsTakePart().size() )
            {
                if( personalPageBean.getEventsTakePart().get( i ).equals(event)== true)
                    personalPageBean.getEventsTakePart().remove( i );
                else
                    i++;
            }
           
        }*/
        // aggiungo a liste dinamiche
        personalPageBean.getEventsTakePart().add(event);
        // se ci sono invitati li salvo nel db
        if(selectedUser!=null && selectedUser.size()>0){
            // controllo che non sia stata invitata due volte la stessa persona
            HashSet hs = new HashSet();
            hs.addAll(selectedUser);
            selectedUser.clear();
            selectedUser.addAll(hs);
            
            invMgr.newInvitations(selectedUser, event);
        }
        Collections.sort(personalPageBean.getEventsTakePart());
        // aggiungo meteo del nuovo evento
        wlmPage.setWeathers(weatherBean.loadWeather(wlmPage.getWeathers(),wlmPage.getEventsTakePart()));
        
        return navigationBean.redirectToPersonalPage();
    }
    
    public String editEvent() throws JSONException, IOException{
        
        System.out.println("Sto per modificare l'evento: "+eventemp.getName());
        eventName = eventemp.getName();
        eventPlace = eventemp.getPlace();
        dateStart = eventemp.getDateStart();
        dateEnd = eventemp.getDateEnd();
        typeIo = eventemp.getTypeIo();
        
        description = eventemp.getDescription();
        
        if(dateEnd==null)
            dateEnd = dateStart;
        if(typePp==true){
            typePpInt = 1;
            System.out.println("sono nell if di typepint e vale: "+typePpInt);
        }
        
        event = new Event(eventName,eventPlace,dateStart,dateEnd,typeIo,typePpInt,description,wlmPage.getUser());
        // aggiorno la lista dinamica
        int i = 0;
        while( i < wlmPage.getEventsTakePart().size() )
        {
            if( wlmPage.getEventsTakePart().get( i ).equals(eventemp)==true){
                wlmPage.getEventsTakePart().remove( i );
                wlmPage.getEventsTakePart().add(event);
                Collections.sort(wlmPage.getEventsTakePart());
                break;
            }else
                i++;
        }
       
        
        eventMgr.editEvent(event, eventemp);
        
        event.setId(eventemp.getId());
        
        if(selectedUser!=null && selectedUser.isEmpty()== false){
            // controllo che non sia stata invitata due volte la stessa persona
            HashSet hs = new HashSet();
            hs.addAll(selectedUser);
            selectedUser.clear();
            selectedUser.addAll(hs);
            
            invMgr.invitaAmici(selectedUser, eventemp, event); 
        }
        
        
        return navigationBean.redirectToPersonalPage();
        
    }
    public void setEventName(String eventName) {
        this.eventName = eventName;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setEventPlace(String eventPlace) {
        this.eventPlace = eventPlace;
    }

    public void setDateStart(Date dateStart) {
        this.dateStart = dateStart;
    }

    public void setDateEnd(Date dateEnd) {
        this.dateEnd = dateEnd;
    }

    public void setTypeIo(int typeIo) {
        this.typeIo = typeIo;
    }
    
    
    public Date getToday() {
        return today;
    }

    public void setToday(Date today) {
        this.today = today;
    }
    
    public int getTypePpInt() {
        return typePpInt;
    }

    public void setTypePpInt(int typePpInt) {
        this.typePpInt = typePpInt;
    }

    public boolean isTypePp() {
        return typePp;
    }

    public void setTypePp(boolean typePp) {
        this.typePp = typePp;
    }

   
       public NavigationBean getNavigationBean() {
        return navigationBean;
    }

    public void setNavigationBean(NavigationBean navigationBean) {
        this.navigationBean = navigationBean;
    }

    public LoginBean getWlmPage() {
        return wlmPage;
    }

    public void setWlmPage(LoginBean wlmPage) {
        this.wlmPage = wlmPage;
    }
    
    public WeatherBean getWeatherBean() {
        return weatherBean;
    }

    public void setWeatherBean(WeatherBean weatherBean) {
        this.weatherBean = weatherBean;
    }

    public PersonalPageBean getPersonalPageBean() {
        return personalPageBean;
    }

    public void setPersonalPageBean(PersonalPageBean personalPageBean) {
        this.personalPageBean = personalPageBean;
    }
    
    
    public String getEventName() {
        return eventName;
    }

    public String getDescription() {
        return description;
    }

    public String getEventPlace() {
        return eventPlace;
    }

    public Date getDateStart() {
        return dateStart;
    }

    public Date getDateEnd() {
        return dateEnd;
    }

    public int getTypeIo() {
        return typeIo;
    }

 

    public Event getEvent() {
    return event;
    }

        
    public List<User> getSelectedUser() {
        return selectedUser;
    }

    public void setSelectedUser(List<User> selectedUser) {
        this.selectedUser = selectedUser;
    }

    public List<User> getUserList() {
        return allUser;
    }

    public void setUserList(List<User> userList) {
        this.allUser = userList;
    }
    public Event getEventemp() {
        return eventemp;
    }

    public void setEventemp(Event eventemp) {
        this.eventemp = eventemp;
    }
}

